let currentCaptchaId = null
let moveBtn = $("#slider-move-btn")

let successCallback
let failCallback
let closeCallback
let validateUrl
let initUrl

function init(options) {
    $('.slider').hide()
    clearAllPreventDefault($(".slider"))

    let {success, fail, checkUrl, generateUrl, close} = options
    validateUrl = checkUrl
    initUrl = generateUrl
    successCallback = success
    failCallback = fail
    closeCallback = close

    // 初始化
    $("#slider-close-btn").click(() => {
        closeCallback && closeCallback()
    })
    $("#slider-refresh-btn").click(() => {
        refreshCaptcha();
    })
    moveBtn.mousedown(down);
    moveBtn.on("touchstart", down);
}

function valid(captchaConfig) {
    let data = {
        bgImageWidth: captchaConfig.bgImageWidth,
        bgImageHeight: captchaConfig.bgImageHeight,
        sliderImageWidth: captchaConfig.sliderImageWidth,
        sliderImageHeight: captchaConfig.sliderImageHeight,
        startSlidingTime: captchaConfig.startTime,
        entSlidingTime: captchaConfig.stopTime,
        trackList: captchaConfig.trackArr
    }
    $.ajax({
        type: "POST",
        url: validateUrl + "?id=" + currentCaptchaId,
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify(data),
        success: function (res) {
            if (res) {
                successCallback && successCallback()
            } else {
                refreshCaptcha();
                failCallback && failCallback()
            }
        }
    })
}

function refreshCaptcha() {
    $('.slider').show()
    $.get(initUrl).done(
        function (data) {
            reset()
            currentCaptchaId = data.id
            const bgImg = $("#bg-img")
            const sliderImg = $("#slider-img")
            bgImg.attr("src", data.captcha.backgroundImage)
            sliderImg.attr("src", data.captcha.sliderImage)
            initConfig(bgImg.width(), bgImg.height(), sliderImg.width(), sliderImg.height(), 206)
        }
    )
}

function doDown() {
    moveBtn.css("background-position", "-5px 31.0092%")
}

function doMove(currentCaptchaConfig) {
    const moveX = currentCaptchaConfig.moveX;
    moveBtn.css("transform", "translate(" + moveX + "px, 0px)")
    $("#slider-img-div").css("transform", "translate(" + moveX + "px, 0px)")
}

function reset() {
    moveBtn.css("background-position", "-5px 11.79625%")
    moveBtn.css("transform", "translate(0px, 0px)")
    $("#slider-img-div").css("transform", "translate(0px, 0px)")
    currentCaptchaId = null;
}